<?php


namespace App\Http\Controllers;
use App\Models\AdminMember;
use Illuminate\Http\Request;
use Illuminate\Routing\Controller;
use Illuminate\Support\Facades\DB;
use PHPMailer\PHPMailer\PHPMailer;

class UserController extends Controller
{
    public function index(){
        return view('kexue.user',['assign'=>getDefault(),'bar'=>bar()]);
    }
    public function sendEmail(Request $request){
        $rand = rand(100000,999999);
        $email = $request -> post('email');
        $mail = new PHPMailer(true);
        $mail->isSMTP(); // tell to use smtp
        $mail->CharSet = "utf-8"; // set charset to utf8
        $mail->SMTPAuth = true;  // use smpt auth
        $mail->SMTPSecure = "ssl"; // or ssl
        $mail->Host = "smtp.qq.com";
        $mail->Port = 465;
        $mail->Username = "1020231546@qq.com";
        $mail->Password = "gljuxojlarzibcig";//去开通的qq或163邮箱中找,这里用的不是邮箱的密码，而是开通之后的一个token

        $mail->setFrom("1020231546@qq.com", "handsome");//设置邮件来源  //发件人
        //标题内容都是网站管理员设定好的
        $mail->Subject = "科学院邮箱验证码"; //邮件标题
        $mail->MsgHTML("您的验证码是:{$rand}");   //邮件内容

        $mail->addAddress($email);  //收件人（用户输入的邮箱）
        $res = $mail->send();
        if($res){
            session(['email_code' => $rand]);
            return response()->json(['code'=>200,'msg'=>'发送成功']);
        }else{
            return response()->json(['code'=>0,'msg'=>'邮件发送失败']);
        }
    }
    //修改密码
    public function changePassword(Request $request){
        $post = $request->post();
        if($post['newPassword'] != $post['confirmPassword']){
            return response()->json(['code'=>0,'msg'=>'两次密码不正确']);
        }
        if ($post['code'] != session('email_code')){
            return response()->json(['code'=>0,'msg'=>'邮箱验证码不正确']);
        }
        $res = AdminMember::find(session('member_id'));
        if ($res -> password == sha1($post['newPassword'])){
            return response()->json(['code'=>0,'msg'=>'与原密码相同 无需修改']);
        }
        $res -> password = sha1($post['newPassword']);
        if ($res ->save()){
            return response()->json(['code'=>200,'msg'=>'修改成功']);
        }
    }

}
